import { DictTag } from "@/components/common/DictTag";
import { addDialog } from "@/components/ReDialog";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { hasAuth } from "@/router/utils";
import { message } from "@/utils/message";
import { handleTree } from "@/utils/tree";
import type { PaginationProps } from "@pureadmin/table";
import { cloneDeep, deviceDetection } from "@pureadmin/utils";
import dayjs from "dayjs";
import { h, nextTick, onMounted, reactive, type Ref, ref, toRaw } from "vue";
import editForm from "../form/index.vue";
import type { FormItemProps } from "../utils/types";

import {
  getProductPage,
  productAdd,
  productDelete,
  productUpdate
} from "@/api/basicArchives/productcate";

const treeLoading = ref(true);
const treeData = ref([]);

export function useProduct(treeRef?: Ref) {
  const form = reactive({
    parentId: undefined
    // type: 1 // 1抓机商品 2兑换礼品
  });

  const loading = ref(false);
  const dataList = ref([]);
  const parentList = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 100]
  });

  const columns: TableColumnList = [
    {
      label: "类目名称",
      prop: "categoryName"
    },
    {
      label: "类目编码",
      prop: "categoryCode"
    },
    {
      label: "上级类目",
      prop: "parentCategoryName",
      cellRenderer: ({ row }) => (
        <>
          <div>{row.parentCategoryName ? row.parentCategoryName : "--"}</div>
        </>
      )
    },
    {
      label: "商品类型",
      prop: "goodsType",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <>
          <DictTag dict-type="PRODUCT_TYPE" dict-value={row.type} />
        </>
      )
    },
    {
      label: "排序",
      prop: "sort"
    },
    {
      label: "创建人",
      prop: "createUserName"
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm"),
      minWidth: 120
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    const params = {
      ...toRaw(form),
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    const { data } = await getProductPage(params);

    dataList.value = data.records;

    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  const formRef = ref();
  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}商品类目`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          categoryName: row?.categoryName ?? undefined,
          categoryCode: row?.categoryCode ?? undefined,
          parentId: row?.parentId ?? form.parentId,
          type: row?.type ?? undefined,
          sort: row?.sort ?? undefined,
          parentList
        }
      },
      width: "500px",
      sureBtnLoading: true,
      fullscreenIcon: true,
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = cloneDeep(options.props.formInline as FormItemProps);
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          setTimeout(() => done(), 800); // 关闭弹窗
          loadTree();
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            delete curData.parentList;
            if (title === "新增") {
              // 表单规则校验通过
              // 实际开发先调用新增接口，再进行下面操作
              const { code } = await productAdd(curData);
              if (code == 200) {
                chores();
              }
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              const { code } = await productUpdate(curData);
              if (code == 200) {
                chores();
              }
            }
          } else {
            closeLoading();
          }
        });
      }
    });
  }

  async function handleDelete(row) {
    const res = await productDelete(row.id);
    if (res.code != 200) return;
    message(`删除成功`, { type: "success" });
    onSearch();
    loadTree();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 加载标签分类菜单tree */
  const loadTree = async () => {
    treeLoading.value = true;
    // 获取菜单
    let params = {
      pageNum: 1,
      pageSize: 999
    };
    const { data } = await getProductPage(params);

    data.records.forEach(item => {
      item.value = item.id;
      item.label = item.categoryName;
    });

    data.records.unshift({
      value: 0,
      id: 0,
      label: "全部",
      categoryName: "全部"
    });

    treeData.value = handleTree(data.records || []);
    // 默认选择第一个
    treeLoading.value = false;
    nextTick(() => {
      let tempData = treeData.value[0];
      treeRef && treeRef.value.setCurrentKey(tempData?.id ?? 0);
    });

    // parentList.value = cloneDeep(data.records);

    parentList.value = handleTree(data.records || []);
  };

  function onTreeSelect(treeData) {
    let { id, selected } = treeData;
    form.parentId = selected && id != 0 ? id : undefined;
    onSearch();
  }

  onMounted(async () => {
    onSearch();
    await loadTree();
    treeLoading.value = false;
  });

  return {
    form,
    columns,
    onSearch,
    loading,
    dataList,
    pagination,
    treeData,
    treeLoading,
    openDialog,
    useRenderIcon,
    handleDelete,
    deviceDetection,
    resetForm,
    handleSizeChange,
    handleCurrentChange,
    onTreeSelect,
    loadTree,
    hasAuth
  };
}
